<template>
    <TodoHeader ref="todoHeader" @add-todo="handleAddTodo"></TodoHeader>
    
    <h2 v-show="todos.length === 0">有事情想要去做吗</h2>
  

      <TodoItem
        v-for="(todo, index) in todos"
        :key="index"
        :todo="todo"
        :index="index"
        @remove-todo="removeTodo"
      ></TodoItem>


    
  
    <TodoFooter
      v-show="todos.length > 0"
      :todos="todos"
      @clear-completed="clearCompleted"
      @clear-all="clearAll"
      @toggle-all="toggleAllCompleted"
    ></TodoFooter>
  </template>
  
  <script setup>
  import { ref, onMounted, watch } from 'vue'
  
  import TodoHeader from './components/TodoHeader.vue'
  import TodoItem from './components/TodoItem.vue'
  import TodoFooter from './components/TodoFooter.vue'
 
  
  const todos = ref([])
  const todoHeader = ref(null)
  
  // 添加事项
  const handleAddTodo = (text) => {
    if (text.trim()) {
      todos.value.push({
        text: text.trim(),
        completed: false
      })
      if (todoHeader.value) {
        console.log(todoHeader.value)
      todoHeader.value.clearInput()
    }
    }
  }
  
  // 删除单个事项
  const removeTodo = (index) => {
    todos.value.splice(index, 1)
  }
  
  // 清除已完成
  const clearCompleted = () => {
    todos.value = todos.value.filter(t => !t.completed)
  }
  
  // 清除所有
  const clearAll = () => {
    todos.value = []
  }
  
  // 全选/全不选
  const toggleAllCompleted = (value) => {
    todos.value.forEach(t => t.completed = value)
  }

  const getTodos = () => {
  const todoLists = JSON.parse(localStorage.getItem('todoLists') || '[]')
  todos.value = todoLists
}
    watch(
        todos,
        () => {
            localStorage.setItem('todoLists', JSON.stringify(todos.value))
        },
        { deep: true }
    )

    onMounted(() => {
        getTodos()
    })

  </script>
  
  <style>
  /* 全局样式 */
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
  h2{
    text-align: center;
}
/* 添加拖拽手柄样式 */
.drag-handle {
  cursor: move;
  margin-right: 10px;
  opacity: 0.5;
}

.drag-handle:hover {
  opacity: 1;
}
  </style>